package com.kingwood.algorithm.test;

import java.util.*;

/**
 * https://blog.csdn.net/qfc_128220/article/details/134387126
 * 智能成绩表
 * 小明来到某学校当老师，需要将学生按考试总分或单科分数进行排名，你能帮帮他吗小明来到某学校当老师，需要将学生按考试总分或单科分数进行排名，你能帮帮他吗？
 */
public class StudentRank {
    static class Student {
        String name;
        int[] rank;
        public Student(String name, int[] rank) {
            this.name = name;
            this.rank = rank;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        System.out.println(n + " " + m);

        HashMap<String, Integer> subjectIndex = new HashMap<>();
        for (int i = 0; i < m; i++) {
            subjectIndex.put(scanner.next(), i);
        }

        ArrayList<Student> students = new ArrayList<>();
        for (int i=0; i<n; i++) {
            String name = scanner.next();
            int[] rank = new int[m+1];
            int sum_score = 0;

            for (int j=0; j<m; j++) {
                rank[j] = scanner.nextInt();
                sum_score += rank[j];
            }

            rank[m] = sum_score;
            students.add(new Student(name, rank));
        }

        String sortXueke = scanner.next();
        System.out.println(sortXueke);
        int sortIndex = subjectIndex.getOrDefault(sortXueke, m);

        students.sort(
                (a, b) ->
                        a.rank[sortIndex] != b.rank[sortIndex]
                                ? b.rank[sortIndex] - a.rank[sortIndex]
                                : a.name.compareTo(b.name)
        );

        StringJoiner sj = new StringJoiner(" ");
        for (Student st : students) {
            sj.add(st.name);
        }

        System.out.println(sj);
    }
}
